<template>
  <div class="home">
    <NavBar :title="title" :status="status" />
    <div class="main">
      <Banner
        :bathVersion="bathInfo.lefttime"
        :mode="bathInfo.mode"
        :status="status"
      />
      <div class="tab-wrapper">
        <div class="mask" v-if="status == 3"></div>

        <van-tabs v-model="active" sticky>
          <van-tab title="控制">
            <!-- 模式 -->
            <!-- 照明与夜灯互斥，不能同时开启  -->
            <!-- 一样的优先级，开了夜灯照明置灰不可动，开了照明夜灯置灰不可动 -->
            <Mode
              :items="modeData"
              :mode="bathInfo.mode"
              :deviceIdentidy="deviceIdentidy"
              @emitUpdateMode="emitUpdateMode"
              @emitSwing="emitSwing"
            />

            <!-- 档位 -->
            <!-- L3, R1不能调节档位 L3=3 R1=2 Z5=1 oxff=4 -->
            <div class="gears" v-if="[1, 4].includes(bathInfo.lefttime)">
              <gear-pannel
                v-if="[360, 332, 359, 356, 789].includes(bathInfo.mode)"
                title="吹风档位"
                :disabled="
                  [356, 789, 455].includes(bathInfo.mode) ? false : true
                "
                gearsKey="windGear"
                :levelVal="Number(bathInfo.windGear)"
                :deviceIdentidy="deviceIdentidy"
              />

              <gear-pannel
                v-if="[474, 789, 455].includes(bathInfo.mode)"
                title="换气档位"
                :levelVal="Number(bathInfo.airChangeGear)"
                gearsKey="airChangeGear"
                :deviceIdentidy="deviceIdentidy"
              />

              <gear-pannel
                v-if="[486, 455].includes(bathInfo.mode)"
                title="取暖档位"
                :levelVal="Number(bathInfo.heatingGear)"
                gearsKey="heatingGear"
                :deviceIdentidy="deviceIdentidy"
              />
            </div>

            <!-- 摆叶可用：待机，取暖 -->
            <cell-pannel
              v-show="bathInfo.lefttime == 4"
              title="摆叶"
              switchKey="angleAutoOnOff"
              :disabled="
                [356, 486, 455, 789].includes(bathInfo.mode) ? false : true
              "
              :checkVal="bathInfo.angleAutoOnOff"
              :swingVal="bathInfo.angleAutoOnOff"
              :deviceIdentidy="deviceIdentidy"
              @emitSwing="emitSwing"
            />
            <!-- 照明与夜灯是互斥的，不能同时开启 -->
            <cell-pannel
              title="照明"
              :deviceIdentidy="deviceIdentidy"
              switchKey="illumination"
              :checkVal="bathInfo.illumination"
              @emitIllumination="emitIllumination"
            />
            <cell-pannel
              title="夜灯"
              switchKey="nightLight"
              subTitle="夜灯定时设置"
              :disabled="nightLightDisabled"
              :lightValue="lightValue"
              :checkVal="bathInfo.nightLight"
              :deviceIdentidy="deviceIdentidy"
              :showTimer="bathInfo.lefttime == 4 ? true : false"
              :timeRange="[
                bathInfo.nightLightStartTime,
                bathInfo.nightLightEndTime
              ]"
              :nightLightStartTime="bathInfo.nightLightStartTime"
              :nightLightEndTime="bathInfo.nightLightEndTime"
              @emitNightLight="emitNightLight"
              @emitSettime="emitSettime"
            />
            <!-- 定时 -->
          </van-tab>
          <van-tab title="口令">
            <command-corpus
              :list="functionCorpus"
              :loading="functionCorpusLoading"
            ></command-corpus>
          </van-tab>
        </van-tabs>
      </div>
    </div>
  </div>
</template>
<script>
// @ is an alias to /src
import NavBar from '@/components/navBar.vue'
import Banner from '@/components/Banner.vue'
import Mode from '@/components/Mode.vue'
import GearPannel from '@/components/GearPannel.vue'
import CellPannel from '@/components/CellPannel.vue'
import CommandCorpus from '@/components/CommandCorpus.vue'

/**
 * device 控制 api：https://help.aliyun.com/document_detail/447470.html?spm=5176.2020520104.0.0.5e183f1bahCP3y
 */
import { device, system, router } from 'aliyun-livinglink-sdk'
import { getQuery } from '@/components/utils'
import { tabItems, modeItems } from '@/utils/enum'
// import { protocolToRawData } from '@/utils/model'
// console.log(tabItems, 'tabItems')
// console.log(
//   protocolToRawData({
//     method: 'thing.service.property.set',
//     id: '12345',
//     version: '1.0',
//     params: { mode: 332 }
//   })
// )

const params = getQuery()
const deviceIdentidy = {
  iotId: params.devId,
  productKey: params.pk,
  skillId: params.skillId
}

export default {
  name: 'HomeView',
  components: {
    NavBar,
    Banner,
    Mode,
    GearPannel,
    CellPannel,
    CommandCorpus
  },

  data() {
    return {
      title: '智能浴霸',
      properties: [],
      deviceProps: {},
      checked: false,
      active: 0,
      tabItems,
      lightValue: '-', // 定时器时间
      gearsDisabled: true,

      /* 属性start*/
      bathInfo: {},
      /* 属性end */
      deviceIdentidy,
      timer: null,
      modeData: [],
      // 指令
      functionCorpus: [],
      functionCorpusLoading: true,
      status: 1, // 设备状态。0（表示未激活）；1（表示在线）；3（表示离线）；8（表示禁用）
      nightLightDisabled: false
    }
  },
  watch: {
    bathInfo: {
      handler(val) {
        const { nightLightStartTime, nightLightEndTime, lefttime, mode } = val
        // 定时
        if (!nightLightStartTime && !nightLightEndTime) {
          this.lightValue = '未设置'
        } else {
          this.lightValue = `${nightLightStartTime}时~${nightLightEndTime}时`
        }
        // 版本
        if (lefttime == 4) {
          this.modeData = [
            ...modeItems,
            ...[
              {
                title: '一键沐浴',
                icon: 'bath',
                id: 359
              }
            ]
          ]
        } else {
          this.modeData = modeItems
        }
        // 模式
        if (mode == 332) {
          this.nightLightDisabled = false
        } else {
          this.nightLightDisabled = true
        }
        // console.log(this.modeData, 'modeData')
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    emitSettime(arr) {
      this.bathInfo.nightLightStartTime = arr[0]
      this.bathInfo.nightLightEndTime = arr[1]
      if (arr[0] == 0 && arr[1] == 0) {
        this.lightValue = '未设置'
      } else {
        this.lightValue = `${arr[0]}时~${arr[1]}时`
      }
    },
    emitUpdateMode(val) {
      this.bathInfo.mode = val
    },
    emitIllumination(val) {
      console.log('emitIllumination:', val)
      if (val == 1) {
        this.bathInfo.nightLight = 0
      }
      this.bathInfo.illumination = val
    },
    emitNightLight(val) {
      if (val == 1) {
        this.bathInfo.illumination = 0
      }
      this.bathInfo.nightLight = val
    },
    emitSwing(val) {
      this.bathInfo.angleAutoOnOff = val
    },
    // 获取设备属性
    getProps() {
      // 获取设备属性
      device
        .getProps(deviceIdentidy)
        .then(res => {
          this.deviceProps = res
          this.bathInfo = res
        })
        .catch(err => {
          console.warn(err)
        })
    },
    async onLeftPress(e) {
      console.log('onLeftPress', e)
      // 退出容器
      await device.unsubscribeAll(deviceIdentidy)
      await router.exit()
    },
    onRightPress(e) {
      console.log('onLeftPress', e)
      // 跳转到设备设置
      router.toDeviceSetting(deviceIdentidy)
    },
    setProps(key, value) {
      // 为了使ui更新更实时，这里组件的更新策略是乐观更新，如果设置失败，会变之前的值
      const preProps = this.deviceProps
      this.deviceProps = {
        ...this.deviceProps,
        [key]: value
      }
      //设置设备属性
      device
        .setProps(deviceIdentidy, { [key]: value })
        .then(res => {
          console.warn('setProps success', res)
        })
        .catch(err => {
          this.deviceProps = preProps
          console.warn(err)
        })
    },
    // 获取语料
    getProductFunctionCorpus() {
      device
        .getFunctionCorpus(deviceIdentidy)
        .then(resp => {
          this.functionCorpus = resp
          this.functionCorpusLoading = false
        })
        .catch(res => {
          this.functionCorpusLoading = false
          console.log('获取语料失败返回', res)
        })
    }
  },
  mounted() {
    // 设置状态栏文字的颜色
    system.setStatusBarStyle('light-content')
    // console.log('mounted1111', this.$el, this.$data)

    // 监听设备属性变化事件
    device.onPropsChange(msg => {
      console.log('监听设备属性变化事件onPropsChange:', msg)
      this.bathInfo = {
        ...this.bathInfo,
        ...msg
      }
    })
    // 获取设备物模型
    device
      .getDeviceTSL(deviceIdentidy)
      .then(res => {
        this.properties = res.properties
      })
      .catch(err => {
        console.warn(err, '获取设备物模型=fail')
      })
    // 获取设备信息
    device
      .getDeviceInfo(deviceIdentidy)
      .then(res => {
        const { productName, devType, alias } = res
        this.title = productName || alias || devType
      })
      .catch(err => {
        console.warn(err, '设备信息 fail')
      })
    // 获取设备状态
    device
      .getStatus(deviceIdentidy)
      .then(res => {
        this.status = res
      })
      .catch(err => {
        console.warn(err, '设备信息 fail')
      })

    this.getProps()
    // 需要先监听事件再订阅设备控制相关事件
    device.subscribeAll(deviceIdentidy)
    // 获取语料
    this.getProductFunctionCorpus()
  }
}
</script>
<style lang="less">
.tab-wrapper {
  position: relative;
  .mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(255, 255, 255, 0.6);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 11;
  }
}
.home {
  display: flex;
  flex-direction: column;
}
.main {
  min-height: calc(100vh - 44px);
  box-sizing: border-box;
  background-color: #f6f6f9;
  padding-bottom: 23px;
  .van-tabs__line {
    background-color: var(--primary-color) !important;
  }
  .van-tab--active {
    color: var(--primary-color);
  }
  .gears {
    margin-bottom: 10px;
  }
}
</style>
